import React, { PureComponent, Fragment } from 'react';
import { connect } from "react-redux";

import { Layout,InputNumber } from 'antd';
import {
    PageHeader,
    ButtonEvent,
    Table,
    Drawer,
    Form,
    Tip
} from '../../../../components';
import { mainService } from '../../../../service';
import { cmsPositionListAction as actionCreates, mainAction } from '../../../../store/action';
import { Luck } from '../../../../utils';

const breadcrumbList = [{
    title:'模块管理'
}, {
    title: '推荐位管理',
    href:'/cms/position'
}, {
    title:'推荐文章列表'
}];

class Index extends PureComponent{

    state = {
        //api名称
        apiname:'cms/positionlist',
        visible:false,
        modalTitle:"推荐",
        //设置表单按钮
        tableBtn:[
			{key:1,type:'danger',value:'移出',onClick:()=>{ this.openModel('del'); }},
			{key:2,value:'保存排序',btnloading:"1",onClick:()=>{ this.saveSort(); }}
        ],
        //表格colums
        columns:[
            {title: '排序',key:'sort',width:120,dataIndex:'sort',sorter:true,render:(value,e)=>{
                return <InputNumber min={0} defaultValue={value} onChange={this.hanadleSortChange.bind(this,e)} />
			}}
			,{title: 'ID',dataIndex:'article_id',width:100}
			,{title: '标题',dataIndex:'title',width:300,onCell: () =>{ return {style: {whiteSpace: 'nowrap',maxWidth: 500}} }}
            ,{title: '发布时间',dataIndex: 'create_time',width:150,sorter:true,render:(value)=>Luck.tamptotime(value,'m') }
            ,{ title: '操作', key: 'operation',fixed:'right', width:200, render: (value) =><ButtonEvent data={ [
                {key:1,value:'原文编辑',size:'small',onClick:()=>{
                    this.editModel(value)
                }},
                {key:2,type:'danger',value:'移出',size:'small',onClick:()=>{
                    this.delModel(value)
                }}
            ]}/> }
        ],
        //form表单
        inputdata : [],
        footerbar:null,
        footBar:[],

        //选中数据
        selectedRowKeys:[],
        selectedRows:[],
        selectedIds:[],
        pagination : {
            current:1,
            onShowSizeChange:(cur,pageSize)=>{this.changeRowsPage(cur,pageSize)},
        }

		,one_id:0
		,oneData:{}
		,sort:[]
	}
	hanadleSortChange = (data, evalue)=>{
		const { sort } = this.state;
		let newsort = sort;
		let flag =true;
		newsort.map((item)=>{
			if(item.id === data.id){
				flag=false;
				item.sort = evalue;
			}
			return item;
		})
		if(flag){
			newsort.push({id:data.id,sort:evalue,article_id:data.article_id})
		}
		this.setState({
			sort:newsort
		})
	}
	saveSort = async ()=>{
		const { sort, apiname } = this.state;
        if(sort.length>0){
			this.changeBtnLoading(true);
            try{
                let res = await mainService.crud(apiname+"/edit",sort);
                this.tipMsg(res);
            }catch{
                this.tipMsg({code:3,msg:"网络错误"});
			}
			this.setState({
				sort:[]
			})
			setTimeout(()=>{
				this.changeBtnLoading(false);
			},500);
        }
	}

    render(){
        const { loading, list, emptyText, total, pageSize, page } = this.props;
        const { tableBtn, columns, visible, modalTitle, inputdata, footerbar, pagination, selectedRowKeys, oneData } = this.state;
        pagination.total = total;
        pagination.current = page;
        pagination.pageSize=pageSize;
        const locale = {
            emptyText
        }
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange
        }

        const action = <ButtonEvent data={ [
            {key:1,type:'primary',value:'刷新',size:'small',onClick:()=>{
                this.reset()
            }}
        ]}/>;
        const title=oneData.hasOwnProperty('name')?"--"+oneData["name"]:"";
        return(
            <Fragment>
                <PageHeader title={breadcrumbList[2]['title']+title} breadcrumbList={breadcrumbList} action={action}></PageHeader>
                
                <Layout.Content style={{margin:'24px',padding:'24px 32px 8px',backgroundColor:'#fff'}}>
                    <ButtonEvent
                        data={ tableBtn }
                        style={{marginBottom:16}}
                    />
                    <Table
                        columns = {columns}
                        dataSource = { list }
                        locale = {locale}
                        loading = { loading }
                        rowSelection={ rowSelection }
                        onChange = { this.handleChange }
                        pagination ={ pagination }
                    />
                </Layout.Content>

                <Drawer title={modalTitle} visible={visible} footBar={footerbar} destroyOnClose={true} maskClosable={true} onClose={this.handleCancel} width="450px">
                    <Form
                        layout = 'horizontal'
                        data = {inputdata}
                        wrappedComponentRef={ (form) => this.formRef = form }
                    />
                </Drawer>
            </Fragment>
        )
    }

    //操作
    openModel=(type)=>{
        const { selectedIds } = this.state;
        switch (type) {
            case 'del':
                if(selectedIds.length > 0){
                    this.delete(selectedIds);
                }else{
                    Tip.Message('至少选择一条数据进行移除','error')
                }
                break;
            default:
                break;
        }
    }
    editModel = (obj)=>{
        const { bindLoading, pageSize, page } = this.props;
        let w=window.screen.width-10;
        let h=window.screen.height-95;
        const win=window.open('about:blank','',"left=10,top=10,width=" + w + ",height=" + h + ",toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no");
        let paramUrl='/'+obj.article_id;
        win.location.href='/cms/article/edit'+paramUrl;

        let loop = setInterval(()=>{   
            if(win.closed) {  
                clearInterval(loop);  
                
                bindLoading(true)
                this.loadList({page,rows:pageSize}) 
            }  
        }, 1000);
    }
    /*editModel = (obj)=>{
        this.setState({
            modalTitle:'修改广告'
        });
        this.editFormJsx(obj);
    }*/
    delModel = (obj)=>{
        let id=[];
        id.push(obj.id)
        this.delete(id);
    }
    //保存按钮状态
    changeBtnLoading = (bool)=>{
        this.props.bindBtnLoading(bool)
    }
    //消息提示
    tipMsg = (res,type='')=>{
        const { bindLoading, bindPage, pageSize, page } = this.props;
        if(res.code===0){
            this.handleCancel();
            Tip.Message(res.msg,'success');
            bindLoading(true);

            if(type==='del'){
                this.loadList({page:1,rows:pageSize})
                bindPage(1);
            }else{
                this.loadList({page,rows:pageSize})
            }
        }else{
            Tip.Message(res.msg,'error')
        }
    }
    //关闭弹窗
    handleCancel=()=>{
        this.setState({
            visible:false
        })
    }
    
    delete = (arr)=>{
        const { apiname } = this.state;
        Tip.Modal('您真的要移除推荐?','confirm',{
            onOk:async ()=>{
                let res = await mainService.crud(apiname+"/del",arr);
                this.tipMsg(res,'del');
            }
        })
    }


    //重置/刷新查询
    reset = () => {
        const { bindLoading, pageSize, page } = this.props;
        bindLoading(true)
        this.loadList({page,rows:pageSize})
    }
    //排序和翻页
    handleChange = (pagination, filters, sorter)=>{
        const { bindLoading } = this.props;
        let order={};
        if(Object.keys(sorter).length>0){
            order={
                field:sorter.field,
                order:sorter.order==="descend" ? 'desc':'asc'
            }
        }
        bindLoading(true)
        this.loadList({page:pagination.current,rows:pagination.pageSize,...order})
    }
    //每页条数
    changeRowsPage = (cur,pagesize)=>{
        const { bindPageSize } = this.props;
        bindPageSize(pagesize);
    }
    //选择
    onSelectChange=(selectedRowKeys, selectedRows) => {
        let newselectedRows=[];
        let selectedIds=[];
        for (let i = 0; i < selectedRows.length; i++) {
            newselectedRows.push(selectedRows[i]);
            selectedIds.push(selectedRows[i].id);
        }
        this.setState({ 
            selectedRowKeys,
            selectedRows:newselectedRows,
            selectedIds
        });
    }

    //获取列表
    loadList = async (data)=>{
        const { bindList, bindPage } = this.props;
        const { apiname, one_id } = this.state;
        data['id']=one_id;
        let res = await mainService.getlist(apiname,data);

        bindList(res);
        bindPage(data.page);
    }

    async componentDidMount(){
        const { pageSize, page, location, history } = this.props;
        const { apiname } = this.state;

        let params = location.search.substr(1).split("&")[0].split("=");
        if(params === "" || params[0] !== "id" || !Number.isInteger(parseFloat(params[1]))){
            history.replace('/cms/position');
        }
        let res = await mainService.find(apiname+"/getone",{
            id:params[1]
		});
		let oneData = {};
		if(res.code!==0){
			oneData["name"]=res.msg
		}else{
			oneData=res.data
		}
        this.setState({
            one_id:params[1],
            oneData
        },()=>{
            this.loadList({page,rows:pageSize})
        });
    }
}

const mapStateToProps = (state)=>{
    const name = 'cms_position_list';
    const list = state.getIn([name,'list']).toJS();
    const loading = state.getIn([name,'loading']);
    const total = state.getIn([name,'total'])
    const formData = state.getIn([name,'formData']).toJS();
    const emptyText = state.getIn([name,'emptyText']);
    
    const page = state.getIn([name,'page']);
    const pageSize = state.getIn([name,'pageSize']);

    const btnloading = state.getIn(['main','btnloading']);

    return{
        list,
        loading,
        total,
        formData,
        emptyText,

        page,
        pageSize,
        btnloading
    }
}
const mapDispatchToProps = (dispatch)=>{
    return{
        bindLoading(loading){
            dispatch(actionCreates.setLoading(loading))
        },
        bindPageSize(pageSize){
            dispatch(actionCreates.setPagesize(pageSize));
        },
        bindPage(page){
            dispatch(actionCreates.setPage(page));
        },
        bindList(res){
            if(res.code === 0){
                let list=res.data;
                dispatch(actionCreates.getList(list.rows,list.total));
            }else{
                dispatch(actionCreates.setEmptyText(res.msg));
            }
            dispatch(actionCreates.setLoading(false));
        },
        bindBtnLoading(bool){
            dispatch(mainAction.setBtnLoading(bool));
        }
    }
}
export default connect(mapStateToProps,mapDispatchToProps)(Index);